package com.qf.controller;


import com.qf.po.Userinfo;
import com.qf.service.UserinfoService;
import com.qf.utils.JwtUtils;
import com.qf.utils.SendUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
@CrossOrigin
public class UserinfoController {
    @Autowired
    UserinfoService userinfoService;

    @RequestMapping(value = "/userinfo",method = RequestMethod.GET)
    public Userinfo login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password, HttpServletRequest request){
        String userId = UUID.randomUUID().toString();
//        生成用户签名
        String token = JwtUtils.sign(userId);
        HttpSession session = request.getSession();
        session.setAttribute("token",token);
        Userinfo userinfo = userinfoService.find(username);
        if (ObjectUtils.isEmpty(userinfo)){
            return null;
        }
        String password1 = userinfo.getPassword();
        if (password.equals(password1)){
            return userinfo;
        }
        return null;
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Userinfo regist(@RequestBody Userinfo userinfo){
        Userinfo adduserinfo = userinfoService.adduserinfo(userinfo);
        if (adduserinfo!=null){
            return adduserinfo;
        }
        return null;
    }
    @RequestMapping(value = "/upd",method = RequestMethod.PUT)
    public Userinfo updat(@RequestBody Userinfo userinfo){
        Userinfo updateuserinfo = userinfoService.updateuserinfo(userinfo);
        if (updateuserinfo!=null){
            return updateuserinfo;
        }
        return null;
    }
    @RequestMapping(value = "/del",method = RequestMethod.DELETE)
    public boolean del(Integer id){
        boolean deluserinfo = userinfoService.deluserinfo(id);
        return deluserinfo;
    }
    @RequestMapping(value = "/sms",method = RequestMethod.GET)
    public String sms(@RequestParam(value = "tel") String tel) throws Exception {
        int i = SendUtils.SendMes(tel);
        if (i==-1){
            return "0";
        }
        String s = String.valueOf(i);
        return s;
    }
}
